<template>
  <div class="my-reviews-container">
    <div class="page-header">
      <h1 class="page-title">我的影评</h1>
      <p class="page-subtitle">记录你的观影感受和评分</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon">📝</div>
        <div class="stat-number">{{ userComments.length }}</div>
        <div class="stat-label">我的评论</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">⭐</div>
        <div class="stat-number">{{ userRatings.length }}</div>
        <div class="stat-label">我的评分</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">🎬</div>
        <div class="stat-number">{{ uniqueMovies.length }}</div>
        <div class="stat-label">评论电影</div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="reviews-section">
      <h3 class="section-title">我的评论</h3>
      <div v-if="userComments.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <div class="empty-text">还没有发表过评论</div>
        <el-button type="primary" @click="goToMovies">去发表评论</el-button>
      </div>
      <div v-else class="comments-list">
        <div v-for="comment in userComments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <div class="movie-info">
              <img 
                :src="getMovieById(comment.movieId)?.poster || 'https://via.placeholder.com/60x90'" 
                :alt="getMovieById(comment.movieId)?.title"
                class="movie-poster"
              />
              <div class="movie-details">
                <h4 class="movie-title" @click="goToMovieDetail(comment.movieId)" style="cursor: pointer; color: #667eea;">{{ getMovieById(comment.movieId)?.title || '未知电影' }}</h4>
                <div class="movie-meta">
                  <span class="movie-year">{{ getMovieById(comment.movieId)?.releaseDate }}</span>
                  <span class="movie-genre">{{ getMovieById(comment.movieId)?.genre }}</span>
                </div>
              </div>
            </div>
            <div class="comment-actions">
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteComment(comment.id)"
                :loading="deletingComment === comment.id"
              >
                删除
              </el-button>
            </div>
          </div>
          <div class="comment-content">
            <p>{{ comment.content }}</p>
          </div>
          <div class="comment-footer">
            <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
            <span class="comment-likes">👍 {{ comment.useful }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 评分列表 -->
    <div class="ratings-section">
      <h3 class="section-title">我的评分</h3>
      <div v-if="userRatings.length === 0" class="empty-state">
        <div class="empty-icon">⭐</div>
        <div class="empty-text">还没有评分记录</div>
        <el-button type="primary" @click="goToMovies">去评分</el-button>
      </div>
      <div v-else class="ratings-list">
        <div v-for="rating in userRatings" :key="rating.id" class="rating-item">
          <div class="rating-header">
            <div class="movie-info">
              <img 
                :src="getMovieById(rating.movieId)?.poster || 'https://via.placeholder.com/60x90'" 
                :alt="getMovieById(rating.movieId)?.title"
                class="movie-poster"
              />
              <div class="movie-details">
                <h4 class="movie-title" @click="goToMovieDetail(rating.movieId)" style="cursor: pointer; color: #667eea;">{{ getMovieById(rating.movieId)?.title || '未知电影' }}</h4>
                <div class="movie-meta">
                  <span class="movie-year">{{ getMovieById(rating.movieId)?.releaseDate }}</span>
                  <span class="movie-genre">{{ getMovieById(rating.movieId)?.genre }}</span>
                </div>
              </div>
            </div>
            <div class="rating-score">
              <span class="score">{{ rating.score }}</span>
              <span class="score-label">分</span>
            </div>
            <div class="rating-actions">
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteRating(rating.id)"
                :loading="deletingRating === rating.id"
              >
                删除
              </el-button>
            </div>
          </div>
          <div class="rating-footer">
            <span class="rating-date">{{ formatDate(rating.createdAt) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/store/authStore'
import { useRouter } from 'vue-router'
import commentApi from '@/api/comment/commentApi.js'
import ratingApi from '@/api/rating/ratingApi.js'
import movieApi from '@/api/movie/movieApi.js'
import { processImageUrl } from '@/utils/imageUtils'

const authStore = useAuthStore()
const router = useRouter()

// 数据
const userComments = ref([])
const userRatings = ref([])
const allMovies = ref([])
const deletingComment = ref(null)
const deletingRating = ref(null)

// 计算属性
const uniqueMovies = computed(() => {
  const movieIds = new Set()
  userComments.value.forEach(comment => movieIds.add(comment.movieId))
  userRatings.value.forEach(rating => movieIds.add(rating.movieId))
  return Array.from(movieIds)
})

// 组件挂载时加载数据
onMounted(() => {
  if (!authStore.user) {
    router.push('/login')
    return
  }
  loadUserReviews()
})

// 加载用户影评数据
async function loadUserReviews() {
  if (!authStore.user) return
  
  try {
    const [commentsRes, ratingsRes, moviesRes] = await Promise.all([
      commentApi.getUserComments(authStore.user.id),
      ratingApi.getUserRatings(authStore.user.id),
      movieApi.getAllMovies()
    ])
    
    userComments.value = commentsRes.data
    userRatings.value = ratingsRes.data
    allMovies.value = moviesRes
  } catch (error) {
    console.error('加载影评数据失败:', error)
  }
}

// 根据ID获取电影信息
function getMovieById(movieId) {
  const movie = allMovies.value.find(movie => movie.id === movieId)
  if (movie && movie.poster) {
    movie.poster = processImageUrl(movie.poster)
  }
  return movie
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 删除评论
async function deleteComment(commentId) {
  if (!confirm('确定要删除这条评论吗？')) return
  
  deletingComment.value = commentId
  try {
    await commentApi.deleteComment(commentId)
    userComments.value = userComments.value.filter(comment => comment.id !== commentId)
    ElMessage.success('评论删除成功')
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败')
  } finally {
    deletingComment.value = null
  }
}

// 删除评分
async function deleteRating(ratingId) {
  if (!confirm('确定要删除这条评分吗？')) return
  
  deletingRating.value = ratingId
  try {
    await ratingApi.deleteRating(ratingId)
    userRatings.value = userRatings.value.filter(rating => rating.id !== ratingId)
    ElMessage.success('评分删除成功')
  } catch (error) {
    console.error('删除评分失败:', error)
    ElMessage.error('删除评分失败')
  } finally {
    deletingRating.value = null
  }
}

// 跳转到电影页面
function goToMovies() {
  router.push('/')
}

// 跳转到电影详情页面
function goToMovieDetail(movieId) {
  router.push({
    path: `/movie/${movieId}`,
    query: { from: 'my-reviews' }
  })
}
</script>

<style scoped>
.my-reviews-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
}

/* 统计信息 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  padding: 30px;
  border-radius: 16px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 评论和评分列表 */
.reviews-section, .ratings-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f2f5;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.comment-item, .rating-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.comment-item:hover, .rating-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.comment-header, .rating-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.movie-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.movie-poster {
  width: 60px;
  height: 90px;
  border-radius: 8px;
  object-fit: cover;
}

.movie-details {
  flex: 1;
}

.movie-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.movie-meta {
  display: flex;
  gap: 12px;
  font-size: 14px;
  color: #666;
}

.comment-content {
  margin-bottom: 16px;
}

.comment-content p {
  color: #333;
  line-height: 1.6;
  margin: 0;
}

.comment-footer, .rating-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #999;
}

.rating-score {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-right: 16px;
}

.score {
  font-size: 24px;
  font-weight: bold;
  color: #ff6b35;
}

.score-label {
  font-size: 14px;
  color: #666;
}

.comment-actions, .rating-actions {
  display: flex;
  gap: 8px;
}

.comment-likes {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-reviews-container {
    padding: 20px 10px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .stats-section {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
  }
  
  .comment-header, .rating-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .movie-info {
    width: 100%;
  }
}
</style> 